//
//  HMComposeTextView.swift
//  WeiBoXR
//
//  Created by acer on 16/9/30.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
@IBDesignable
class HMComposeTextView: UITextView {

    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "别低头,绿帽会掉~"
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        return label
    }()
    //  提供设置占位文字属性
    @IBInspectable var placeHolder : String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    override var text: String? {
        didSet {
            placeHolderLabel.isHidden = hasText
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupUI()
    }


    private func setupUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
//        backgroundColor = RandomColor()
        addSubview(placeHolderLabel)
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }
    
    @objc private func textChange() {
        placeHolderLabel.isHidden = hasText
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
